﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;


namespace Net6Template.Tools
{
    public static class EnumHelper
    {

        /// <summary>
        /// 获取枚举类型的Description
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToEnumDescription<TEnum>(this TEnum value) where TEnum : struct
        {
            Type type = typeof(TEnum);
            if (!type.IsEnum)
            {
                throw new ArgumentException("TEnum requires a Enum", "TEnum");
            }
            var name = Enum.GetName(type, value);
            if (!string.IsNullOrEmpty(name))
            {
                var field = type.GetField(name);
                return field?.GetCustomAttribute<DescriptionAttribute>()?.Description;
            }
            return "";
        }

        public static TEnum ToEnumFromDescription<TEnum>(this string value) where TEnum : struct
        {
            return (TEnum)typeof(TEnum)
                .GetFields()
                .Select(field => new { Field = field, Description = field.GetCustomAttribute<DescriptionAttribute>() })
                .First(info => info.Description.Description == value)
                .Field.GetValue(null);
        }

        public static string ToEnumDescription<TEnum>(this int value) where TEnum : struct
        {
            return ((TEnum)(dynamic)value).ToEnumDescription();
        }

        /// <summary>
        ///     获取某个枚举类型的数据源，数据源是描述和值的组合，返回字段是 Key(description)/Value(int)
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <returns>集合</returns>
        public static List<DictionaryEntry> GetBindData<TEnum>()
        {
            List<DictionaryEntry> obj = ResolveEnum<TEnum>();

            return obj;
        }


        private static List<DictionaryEntry> ResolveEnum<TEnum>()
        {
            Type type = typeof(TEnum);

            if (!type.IsEnum)
            {
                throw new ArgumentException("TEnum requires a Enum", "TEnum");
            }

            FieldInfo[] fields = type.GetFields();

            var col = new List<DictionaryEntry>();

            foreach (FieldInfo field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (objs != null && objs.Length > 0)
                {
                    var attr = objs[0] as DescriptionAttribute;

                    col.Add(new DictionaryEntry(attr.Description, ((int)Enum.Parse(type, field.Name)).ToString()));
                }
            }

            return col;
        }

    }
}
